package cn.com.code.design.agent;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.FactoryBean;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

/**
 * 代理类定义
 *
 * @author zhengpei
 * @date 2021/10/23
 */
public class MapperFactoryBean<T> implements FactoryBean<T> {

  private static final Logger logger = LoggerFactory.getLogger(MapperFactoryBean.class);

  private Class<T> mapperInterface;

  public MapperFactoryBean(Class<T> mapperInterface) {
    this.mapperInterface = mapperInterface;
  }

  @Override
  public T getObject() throws Exception {
    InvocationHandler handler = (proxy, method, args) -> {
      Select select = method.getAnnotation(Select.class);
      logger.info("SQL:{}", select.value().replace("#{userId}", args[0].toString()));
      return args[0] + "everything will be fine";
    };
    return (T) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[]{mapperInterface}, handler);
  }

  @Override
  public Class<?> getObjectType() {
    return mapperInterface;
  }

  @Override
  public boolean isSingleton() {
    return true;
  }

}
